package com.hncj.controller;

import com.hncj.pojo.Kind;
import com.hncj.result.R;
import com.hncj.service.KindService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/kinds")
public class kindController {

    @Autowired
    private KindService kindService;

    @GetMapping("/list")
    public R<List<Kind>> getList(){
        return R.success(kindService.list());
    }

    @PostMapping
    public R<String> insert(@RequestBody String name) throws UnsupportedEncodingException {
        Kind kind=new Kind();
        name= URLDecoder.decode(name, "UTF-8");
        System.out.println("未处理的分类名:"+name);
        name=name.split("=")[0];
        kind.setName(name);
        kindService.save(kind);
        return R.success("新增成功！");
    }

    @PutMapping
    public R<String> update(@RequestBody Kind kind) {
        System.out.println("未处理的kind:"+kind.toString());
        return kindService.updateById(kind)?R.success("更新成功"):R.error("更新失败");
    }

    @DeleteMapping
    public R<String> deleteById(@RequestBody Integer[] ids){

        System.out.println("执行删除的KindIds:"+Arrays.toString(ids));

        for(int i : ids){
            kindService.removeById(i);
        }

        return R.success("已删除");
    }

}
